import React from 'react';
import { useNavigate } from 'react-router-dom';
import {
    Card,
    CardContent,
    CardActions,
    Typography,
    Box,
    IconButton,
    Tooltip,
    CardMedia,
    Chip
} from '@mui/material';
import { styled } from '@mui/material/styles';
import {
    Edit as EditIcon,
    Delete as DeleteIcon,
    Visibility as ViewIcon,
    ViewInAr as ModelIcon
} from '@mui/icons-material';
// 导入3D几何体相关图标
import {
    ViewInAr as CubeIcon,
    Category as GeometryIcon,
    SportsVolleyball as SphereIcon
} from '@mui/icons-material';
import { motion } from 'framer-motion';

const StyledCard = styled(motion(Card))(({ theme }) => ({
    height: '100%',
    display: 'flex',
    flexDirection: 'column',
    transition: 'all 0.3s ease-in-out',
    '&:hover': {
        transform: 'translateY(-4px)',
        boxShadow: theme.shadows[8],
    },
}));

// 几何体类型图标映射
const geometryTypeIcons = {
    'cube': <CubeIcon fontSize="small" />,
    'sphere': <SphereIcon fontSize="small" />,
    'cylinder': <GeometryIcon fontSize="small" />,
    'cone': <GeometryIcon fontSize="small" />,
    'plane': <GeometryIcon fontSize="small" />
};

// 几何体类型显示名称
const geometryTypeNames = {
    'cube': '立方体',
    'sphere': '球体',
    'cylinder': '圆柱体',
    'cone': '圆锥体',
    'plane': '平面'
};

const ModelCard = ({ model, onDelete }) => {
    const navigate = useNavigate();
    // 从model中解构，优先使用id
    const { id, name, description, createdAt, geometry } = model || {};

    // 确保id存在
    if (!id) {
        console.error('ModelCard: 模型对象缺少ID', model);
    }

    // 是否为几何体模型
    const isGeometryModel = !!geometry;

    // Format date
    const formattedDate = createdAt ? new Date(createdAt).toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric'
    }) : '未知日期';

    const handleEdit = () => {
        if (!id) {
            console.error('无法编辑，模型ID缺失');
            return;
        }
        if (isGeometryModel) {
            navigate(`/models/geometry/edit/${id}`);
        } else {
            navigate(`/models/edit/${id}`);
        }
    };

    const handleView = () => {
        if (!id) {
            console.error('无法查看，模型ID缺失');
            return;
        }
        // 导航到模型详情页面
        navigate(`/models/view/${id}`);
    };

    const handleDelete = (e) => {
        e.stopPropagation();
        if (!id) {
            console.error('删除按钮被点击，但模型ID缺失');
            return;
        }
        console.log('删除按钮被点击，模型ID:', id, '模型名称:', name);
        if (onDelete) {
            console.log('调用onDelete回调，模型ID:', id);
            onDelete(id);
        } else {
            console.error('onDelete回调未定义');
        }
    };

    const handleFilesClick = () => {
        if (!id) {
            console.error('无法访问文件，模型ID缺失');
            return;
        }
        navigate(`/models/${id}/files`);
    };

    const handleCardClick = () => {
        handleView(); // 点击卡片时也导航到模型详情
    };

    return (
        <StyledCard
            whileHover={{ y: -5 }}
            transition={{ type: 'spring', stiffness: 300 }}
            onClick={handleCardClick}
            sx={{ cursor: 'pointer' }}
        >
            <CardMedia
                component="div"
                sx={{
                    height: 140,
                    backgroundColor: isGeometryModel ? geometry.color : 'primary.light',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    position: 'relative'
                }}
            >
                <Box
                    component="img"
                    src={`https://source.unsplash.com/random/300x200/?3d,model&sig=${id}`}
                    alt={name}
                    sx={{
                        width: '100%',
                        height: '100%',
                        objectFit: 'cover',
                    }}
                />
                {isGeometryModel && (
                    <Chip
                        icon={geometryTypeIcons[geometry.type] || <GeometryIcon fontSize="small" />}
                        label={geometryTypeNames[geometry.type] || geometry.type}
                        size="small"
                        sx={{
                            position: 'absolute',
                            top: 8,
                            right: 8,
                            backgroundColor: 'rgba(255, 255, 255, 0.9)'
                        }}
                    />
                )}
            </CardMedia>
            <CardContent sx={{ flexGrow: 1 }}>
                <Typography variant="h6" component="h2" gutterBottom noWrap>
                    {name}
                </Typography>
                <Typography variant="body2" color="text.secondary" sx={{
                    overflow: 'hidden',
                    textOverflow: 'ellipsis',
                    display: '-webkit-box',
                    WebkitLineClamp: 2,
                    WebkitBoxOrient: 'vertical',
                    mb: 1
                }}>
                    {description || '无描述'}
                </Typography>
                <Typography variant="caption" color="text.secondary">
                    创建于: {formattedDate}
                </Typography>
            </CardContent>
            <CardActions sx={{ justifyContent: 'space-between', px: 2, pb: 2 }}>
                <Box>
                    <Tooltip title="查看模型">
                        <IconButton
                            size="small"
                            color="primary"
                            onClick={(e) => {
                                e.stopPropagation();
                                handleView();
                            }}
                        >
                            <ViewIcon />
                        </IconButton>
                    </Tooltip>
                    <Tooltip title="文件管理">
                        <IconButton
                            size="small"
                            color="primary"
                            onClick={(e) => {
                                e.stopPropagation();
                                handleFilesClick();
                            }}
                        >
                            <ModelIcon />
                        </IconButton>
                    </Tooltip>
                </Box>
                <Box>
                    <Tooltip title="编辑">
                        <IconButton
                            size="small"
                            color="primary"
                            onClick={(e) => {
                                e.stopPropagation();
                                handleEdit();
                            }}
                        >
                            <EditIcon />
                        </IconButton>
                    </Tooltip>
                    <Tooltip title="删除">
                        <IconButton size="small" color="error" onClick={handleDelete}>
                            <DeleteIcon />
                        </IconButton>
                    </Tooltip>
                </Box>
            </CardActions>
        </StyledCard>
    );
};

export default ModelCard; 